#!/bin/bash

reboot_flag=0
echo -e "\e[33mAre you sure to copy file system?(y/n)\e[0m"
while [ 1 ];do
	if [ -z ${ch_sys} ];then
		read ch_sys
	fi
	break
done

if [ "${ch_sys}" == "y" ];then
	num=`find /dev -name "sd*[0-9]" -o -name "nvme0n1p[0-9]"| wc -l`
	echo -e "\nChoose device :"
	for ((i = 1; i <= ${num}; i++))
	do
	        dev_name[$i]=`find /dev -name "sd*[0-9]" -o -name "nvme0n1p[0-9]" | head -n $i | tail -n 1`
	        dev_size[$i]=`sudo fdisk -l | grep ${dev_name[$i]} | awk '{print $5}'`
	        echo -e "$i. ${dev_name[$i]}    ${dev_size[$i]}"
	done
	
	while [ 1 ];
	do
	        #input
	        echo -e "\nInput device num"
	
	        read opt
	        #echo ${opt}
	
	        if [ -z "${opt}" ];then
	                echo -e "Please input!\n"
       	        	continue
       		fi

        	#judge number
        	if [ ! -z "`echo ${opt} | grep [^0-9]`" ];then
                	echo -e "Please Enter the Right Number!\n"
                	sleep 0.5
                	continue
        	fi

        	#judge range
        	if [ ${opt} -gt ${num} ];then
        	        echo -e "Number too large!\n"
	                sleep 0.5
        	        continue
        	fi

		#judge device
		echo -e "\nEnsure the device : ${dev_name[${opt}]} (y/n)"
		while [ 1 ];do
			if [ -z $com ];then
				read com
			fi
			break
		done
		if [ "${com}" == "y" ];then
			break
		fi
		unset com

	done
fi

echo -e "\nStart to mount ${dev_name[${opt}]}\n"
sudo umount ${dev_name[${opt}]}
sudo rm -rf /data_temp
sudo mkdir -p /data_temp
sudo mount ${dev_name[${opt}]} /data_temp

if [ $? != 0 ]; then
        echo -e "\nMount ${dev_name[${opt}]} failed, exit\n"
	exit
fi

sudo rm -rf /data_temp/* 

sudo cp -rfp /bin/ /data_temp/.
sudo sync
sudo cp -rfp /boot/ /data_temp/.
sudo sync
sudo cp -rfp /etc/ /data_temp/.
sudo sync
sudo cp -rfp /home/ /data_temp/.
sudo sync
sudo cp -rfp /lib/ /data_temp/.
sudo sync
sudo cp -rfp /opt/ /data_temp/.
sudo sync
sudo cp -rfp /root/ /data_temp/.
sudo sync
sudo cp -rfp /sbin/ /data_temp/.
sudo sync
sudo cp -rfp /snap/ /data_temp/.
sudo sync
sudo cp -rfp /srv/ /data_temp/.
sudo sync
sudo cp -rfp /usr/ /data_temp/.
sudo sync
sudo cp -rfp /var/ /data_temp/.
sudo sync

sudo mkdir -p /data_temp/dev
sudo mkdir -p /data_temp/mnt
sudo mkdir -p /data_temp/media
sudo mkdir -p /data_temp/proc
sudo mkdir -p /data_temp/sys
sudo mkdir -p /data_temp/tmp
sudo mkdir -p /data_temp/run
sudo chmod 777 -R /data_temp/tmp

sudo sync
sudo sync
sudo sync
sudo sync

if [ $? == 0 ]; then
	echo -e "\nFile system copy success!\n"
fi
